package middleware

import (
	"gin-project/models"
	"gin-project/utils"

	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
)

func AuthMiddleware() gin.HandlerFunc{
	return func(c *gin.Context) {
		// 从请求头获取令牌
		tokenStr := c.GetHeader("Authorization")
		// 使用zap打印不同级别的日志
		utils.Logger.Info(
			"开始查询用户",
			zap.String("tokenStr=====", tokenStr),     
		)

		if tokenStr == "" {
			utils.Unauthorized(c, "未提供令牌")
			c.Abort()
			return
		}
		// 验证令牌
		token ,err := models.ValidateToken(tokenStr)
		if err != nil{
			utils.Unauthorized(c, "无效的令牌或令牌已过期")
			c.Abort()
			return
		}
		c.Set("userId",token.UserID)
		c.Next()

	}
}